package com.cqut.forum.service.imp;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;

import com.cqut.forum.dao.ArticleDao;
import com.cqut.forum.dao.ArticleReplyDao;
import com.cqut.forum.dao.MessagesDao;
import com.cqut.forum.dao.ModuleDao;
import com.cqut.forum.dao.PictureReplyDao;
import com.cqut.forum.dao.RelationDao;
import com.cqut.forum.dao.RoleDao;
import com.cqut.forum.dao.UserDao;
import com.cqut.forum.dao.UserLogDao;
import com.cqut.forum.dao.UserNewsDao;
import com.cqut.forum.entity.Messages;
import com.cqut.forum.entity.Role;
import com.cqut.forum.entity.User;
import com.cqut.forum.entity.UserLog;
import com.cqut.forum.service.UserService;

/**
 * 用户service实现类
 * @author yangxun
 */
@Controller
public class UserServiceImp implements UserService {

	@Resource
	private UserDao userDao;
	@Resource
	private UserLogDao userLogDao;
	@Resource
	private MessagesDao messagesDao;
	@Resource
	private RoleDao roleDao;
	@Resource
	private RelationDao relationDao;
	@Resource
	private UserNewsDao userNewsDao;
	@Resource
	private ArticleDao articleDao;
	@Resource
	private ArticleReplyDao articleReplyDao;
	@Resource
	private PictureReplyDao pictureReplyDao;
	@Resource
	private ModuleDao moduleDao;
	
	public User getByName(String userName) {
		User user = userDao.getUser(userName);
		return user;
	}
	public User getById(int userId) {
		User user = userDao.get(userId, User.class);
		return user;
	}
	
	@Transactional
	public User register(User user) {
		//获取用户角色
		Role role = roleDao.getRole("会员");
		
		user.setRole(role);
		//设置注册时间
		user.setUserTime(new Date());
		user.setUserLastLoginTime(user.getUserTime());
		user.setUserPhoto("../../left1.jpg");
		user.setUserState(true);
		userDao.save(user);
		//添加用户注册成功的日志
		UserLog userLog = new UserLog();
		userLog.setUser(user);
		userLog.setUserLogTime(user.getUserTime());
		userLog.setUserLogContents("用户名为"+user.getUserName()+"已经注册成功！");
		userLogDao.save(userLog);
		
		//新添加一条系统留言信息欢迎新用户
		Messages messages = new Messages();
		messages.setUser(user);
		messages.setAboveMessagesId(null);
		messages.setMessagesTime(new Date());
		messages.setLastReplyTime(messages.getMessagesTime());
		messages.setMessagesState("未读");
		messages.setMessagesContents("尊敬的"+user.getUserName()+"欢迎加入Pea tips大家庭！");
		messages.setAcceptUserId(user.getUserId());
		messages.setAboveMessagesId(-1);
		messagesDao.save(messages);
		System.out.println("用户注册成功！");
	
		return user;
	}

	@Override
	public User update(User user) {
		return userDao.update(user);
	}
	
	@SuppressWarnings("deprecation")
	public List<Map<String, Object>> getActiveInfo(User user,boolean isCare,int inde,int size){
		int moduleId = moduleDao.getModuleIndex("动态");
		List<Map<String, Object>> activeInfo = new ArrayList<Map<String,Object>>();
		List<Map<String, Object>> actives = null;
		if(isCare){
			actives = articleDao.getCareUnread(user.getUserId(),moduleId, inde, 5);
		}
		else{
			actives = articleDao.getAllUnread(user.getUserId(),moduleId, inde, size);
		}
		List<Map<String, Object>> articleReplys = new ArrayList<Map<String,Object>>();
		List<Map<String, Object>> pictureReplys = new ArrayList<Map<String,Object>>();
		//获取动态评论内容
		if(actives.size()>0){
			List<Integer> articleIds = new ArrayList<Integer>();
			List<Integer> pictureIds = new ArrayList<Integer>();
			for(int i=0;i<actives.size();i++){
				//articleIds[i] = (Integer) actives.get(i).get("target_id");
				String isPublic = (String) actives.get(i).get("is_picture");
				if(isPublic.equals("true")){
					pictureIds.add((Integer)actives.get(i).get("target_id"));
				}
				else{
					articleIds.add((Integer)actives.get(i).get("target_id"));
				}
			}
			if(articleIds.size()>0)
				articleReplys = articleReplyDao.getArticleReplys(articleIds);
			if(pictureIds.size()>0)
				pictureReplys = pictureReplyDao.getPictureReplys(pictureIds);
		}
		
		for(Map<String, Object> map:actives){
			Map<String,Object> m = new HashMap<String, Object>();
			m.put("userId", map.get("user_id"));
			m.put("image", map.get("user_photo"));
			m.put("name", map.get("user_name"));
			m.put("content", map.get("contents"));
			m.put("time", ((Date)map.get("create_time")).toLocaleString());
			//如果if判断为false，则该map存储内容为article，否则为picture
			if(map.get("is_picture").equals("false")){
				m.put("articleId", map.get("target_id"));
				List<Map<String, Object>> reply = new ArrayList<Map<String,Object>>();
				for(Map<String, Object> r:articleReplys){
					if(map.get("target_id").equals(r.get("article_id"))){
						Map<String, Object> rep = new HashMap<String, Object>();
						rep.put("userId", r.get("user_id"));
						rep.put("image", r.get("user_photo"));
						rep.put("name", r.get("user_name"));
						rep.put("content", r.get("article_reply_contents"));
						rep.put("time", ((Date)r.get("article_reply_time")).toLocaleString());
						reply.add(rep);
					}
				}
				m.put("reply", reply);
			}
			else{
				m.put("pictureId", map.get("target_id"));
				//m.put("pictureAddress", map.get("picture_address"));
				//m.put("time", ((Date)map.get("upload_time")).toLocaleString());
				List<Map<String, Object>> reply = new ArrayList<Map<String,Object>>();
				for(Map<String, Object> r:pictureReplys){
					if(map.get("target_id").equals(r.get("picture_id"))){
						Map<String, Object> rep = new HashMap<String, Object>();
						rep.put("userId", r.get("user_id"));
						rep.put("image", r.get("user_photo"));
						rep.put("name", r.get("user_name"));
						rep.put("content", r.get("review_contents"));
						rep.put("time", ((Date)r.get("review_time")).toLocaleString());
						reply.add(rep);
					}
				}
				m.put("reply", reply);
			}
			activeInfo.add(m);
		}
		
		return activeInfo;
	}
	
	public Map<String, Object> getUserBasicInfo(User user) {
		Map<String,Object> userBase = new HashMap<String, Object>();
		userBase.put("userPicture", user.getUserPhoto());
		userBase.put("userName", user.getUserName());
		userBase.put("userId", user.getUserId());
		//userBase.put("user_care", "0");
		userBase.put("userFriends", relationDao.getFriendsSize(user.getUserId()));
		userBase.put("userScore", user.getUserScore()==null?0:user.getUserScore());
		return userBase;
	}

	public Map<String, Object> getUserNotice(User user) {
		Map<String,Object> userNotice = new HashMap<String, Object>();
		int am = moduleDao.getModuleIndex("博客");
		int dm = moduleDao.getModuleIndex("帖子");
		//userNotice.put("friendsNotice", userNewsDao.getFriendUnreadNotice(user.getUserId()));
		userNotice.put("careNotice", userNewsDao.getCareUnreadNotice(user.getUserId()));
		int messageNotice = messagesDao.getUnreadSize(user.getUserId());
		userNotice.put("messageNotice", messageNotice);
		userNotice.put("articleNotice",userNewsDao.getArticleUnreadNotice(user.getUserId(),am));
		userNotice.put("discussNotice", userNewsDao.getDiscussUnreadNotice(user.getUserId(),dm));
		userNotice.put("pictureNotice", userNewsDao.getPictureUnreadNotice(user.getUserId()));
		userNotice.put("applyNotice", relationDao.applyCount(user.getUserId(), "申请"));
		
		return userNotice;
	}

	@SuppressWarnings("unchecked")
	public List<Map<String, String>> getVisit(User user) {
		List<Map<String, String>> visitHistory = new ArrayList<Map<String,String>>();
		List<Map> list = (List<Map>) userNewsDao.getVisitMe(user.getUserId());
		
		for(Map map:list){
			Map<String,Object> m = new HashMap<String, Object>();
			m.put("userId", m.get("user_id"));
			m.put("image", map.get("user_photo"));
			m.put("name", map.get("user_name")); 
			m.put("time", map.get("news_time"));
			visitHistory.add(map);
		}
		
		return visitHistory;
	}
	
	public List<Map<String, Object>> getFriends(User user) {
		List<Map<String, Object>> userFriends = new ArrayList<Map<String,Object>>();
		List<Map<String, Object>> friends = relationDao.getFriends(user.getUserId(),0,10);
		for(Map<String, Object> u:friends){
			Map<String, Object> f = new HashMap<String, Object>();
			f.put("userId", u.get("user_id")+"");
			f.put("image", u.get("user_photo"));
			f.put("name", u.get("user_name"));
			f.put("news", null==u.get("user_sign")?"":"");
			userFriends.add(f);
		}
		return userFriends;
	}

	@Override
	public List<Map<String, Object>> getMostScore(int index, int size) {
		List<Map<String, Object>> users = userDao.getMostScore(index,size);
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		
		for(Map<String, Object> map:users){
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("userId", map.get("user_id"));
			m.put("userName", map.get("user_name"));
			m.put("userPhoto", map.get("user_photo"));
			m.put("userScore", map.get("user_score"));
			m.put("userSex", map.get("user_sex"));
			result.add(m);
		}
		
		return result;
	}
	
	@SuppressWarnings("unused")
	private User updateUser(User newUser,User oldUser){
		newUser.setUserBirthday(oldUser.getUserBirthday().equals(null)?null:oldUser.getUserBirthday());
		newUser.setUserEmail(oldUser.getUserEmail().equals(null)?null:oldUser.getUserEmail());
		newUser.setUserLastLoginTime(oldUser.getUserLastLoginTime().equals(null)?null:oldUser.getUserLastLoginTime());
		newUser.setUserName(oldUser.getUserName().equals(null)?null:oldUser.getUserName());
		return newUser;
	}
	@Override
	public int getUserRank(int userId) {
		int rankNum = userDao.getUserRank(userId);
		return rankNum;
	}
	
	@Override
	public List<User> fishUser(int index, int size) {
		List<User> result = userDao.getFishUser(index,size);
		return result;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public List<Map<String, Object>> getUserInfo(User user, int inde, int size) {
		int moduleId = moduleDao.getModuleIndex("动态");
		List<Map<String, Object>> activeInfo = new ArrayList<Map<String,Object>>();
		List<Map<String, Object>> actives = articleDao.getUserInfo(user.getUserId(),moduleId, inde, size);
		
		List<Map<String, Object>> articleReplys = new ArrayList<Map<String,Object>>();
		//获取动态评论内容
		if(actives.size()>0){
			List<Integer> articleIds = new ArrayList<Integer>();
			for(int i=0;i<actives.size();i++){
				articleIds.add((Integer)actives.get(i).get("article_id"));
			}
			articleReplys = articleReplyDao.getArticleReplys(articleIds);
		}
		
		for(Map<String, Object> map:actives){
			Map<String,Object> m = new HashMap<String, Object>();
			m.put("userId", map.get("user_id"));
			m.put("image", map.get("user_photo"));
			m.put("name", map.get("user_name"));
			m.put("content", map.get("article_contents"));
			m.put("time", ((Date)map.get("publish_time")).toLocaleString());
			m.put("articleId", map.get("article_id"));
			List<Map<String, Object>> reply = new ArrayList<Map<String,Object>>();
			for(Map<String, Object> r:articleReplys){
				if(map.get("article_id").equals(r.get("article_id"))){
					Map<String, Object> rep = new HashMap<String, Object>();
					rep.put("userId", r.get("user_id"));
					rep.put("image", r.get("user_photo"));
					rep.put("name", r.get("user_name"));
					rep.put("content", r.get("article_reply_contents"));
					rep.put("time", ((Date)r.get("article_reply_time")).toLocaleString());
					reply.add(rep);
				}
			}
			m.put("reply", reply);
			activeInfo.add(m);
		}
		
		return activeInfo;
	}
	/***********get and set method****************/
	public UserDao getUserDao() {
		return userDao;
	}
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	public UserLogDao getUserLogDao() {
		return userLogDao;
	}
	public void setUserLogDao(UserLogDao userLogDao) {
		this.userLogDao = userLogDao;
	}
	public MessagesDao getMessagesDao() {
		return messagesDao;
	}
	public void setMessagesDao(MessagesDao messagesDao) {
		this.messagesDao = messagesDao;
	}
	public RoleDao getRoleDao() {
		return roleDao;
	}
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}
	public RelationDao getRelationDao() {
		return relationDao;
	}
	public void setRelationDao(RelationDao relationDao) {
		this.relationDao = relationDao;
	}

	public UserNewsDao getUserNewsDao() {
		return userNewsDao;
	}

	public void setUserNewsDao(UserNewsDao userNewsDao) {
		this.userNewsDao = userNewsDao;
	}

	public ArticleDao getArticleDao() {
		return articleDao;
	}

	public void setArticleDao(ArticleDao articleDao) {
		this.articleDao = articleDao;
	}

	public User login(String userName, String password) {
		User user = userDao.getUser(userName, password);
		return user;
	}
	@Override
	public int getUserRoleId(String roleName) {
		Role role = roleDao.getRole("管理员");
		return role.getRoleId();
	}
}
